import type { Router, RouteRecordRaw } from 'vue-router'

import { usePermissionStoreWithOut } from '/@/store/modules/permission'

import { PageEnum } from '/@/enums/pageEnum'
import { useUserStoreWithOut } from '/@/store/modules/user'
import { useAppStoreWithOut } from '/@/store/modules/app'
import { setBarStatus } from '/@/utils/guideBar'


import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic'

import { RootRoute } from '/@/router/routes'

const LOGIN_PATH = PageEnum.BASE_LOGIN

const JD_CONFIRM = PageEnum.JD_CONFIRM

const ROOT_PATH = RootRoute.path

const whitePathList: PageEnum[] = [LOGIN_PATH, JD_CONFIRM]

import { useMessage } from '/@/hooks/web/useMessage'

const { createErrorModal } = useMessage()

import behavior from '/@/utils/behavior'  //行为检测
import { message } from 'ant-design-vue' //提示
import { sseService } from '/@/utils/sse' //sse连接

import { h, computed } from 'vue'

import { useGlobSetting } from '/@/hooks/setting'
const globSetting = useGlobSetting()


export function createPermissionGuard(router: Router) {
  const userStore = useUserStoreWithOut()
  const appStore = useAppStoreWithOut()
  const permissionStore = usePermissionStoreWithOut()
  const addSubjectForm = computed(() => userStore.getSysConfig)
  const authorityInfo = computed(() => userStore.getAuthorityItem)


  router.beforeEach(async (to, from, next) => {
    if (
      from.path === ROOT_PATH &&
      to.path === PageEnum.BASE_HOME &&
      userStore.getUserInfo.homePath &&
      userStore.getUserInfo.homePath !== PageEnum.BASE_HOME
    ) {
      next(userStore.getUserInfo.homePath)
      return
    }

    const token = userStore.getToken;


    if (token) {

      if (authorityInfo.value?.roleCode === 'PYJS') {
        if (to.name === "TeacherChoice" || to.name === "Review") {
          setBarStatus(false, false) // 评阅页面隐藏顶部、左侧菜单
        } else {
          setBarStatus(false, true) // 评阅页面教师隐藏左侧菜单
        }
        appStore.setShowTopMenu(false)
      } else {
        setBarStatus(true, false)
        appStore.setShowTopMenu(true)
      }

      // sse连接
      // !userStore.userMySse && (async () => {
      //   await sseService.disconnect(userStore.getUserInfo.account, userStore.getUserInfo.device);
      //   userStore.setUserMySse(sseService);
      //   userStore.userMySse.connect({
      //     url: `${globSetting.sseApi}/sse/createSseConnect?account=${userStore.getUserInfo.account}&device=${userStore.getUserInfo.device}&eventName=myMessage`,
      //     onmessage(event) {
      //       console.log('sseService', "myMessage", event);

      //     },
      //     onopen() {
      //       console.log('sseService', '连接成功');
      //     },
      //     finallyHandler() {
      //       console.log('sseService', "触发了");
      //     },
      //     onModifyYear(event) {
      //       sseService.disconnect(userStore.getUserInfo.account, userStore.getUserInfo.device)//断开连接
      //       console.log('sseService', "修了改年", event);
      //       if (event.data == '修改了年份') {
      //         createErrorModal({
      //           iconType: 'warning',
      //           title: () => h('span', '温馨提醒'),
      //           content: () => h('span', '管理员修改年,请重新登录'),
      //           onOk: async () => {
      //             userStore.logout(true)
      //           },
      //         })
      //       }
      //     },
      //   })
      // })();


      await userStore.setSysConfig()//获取系统配置

      // 用户行为检测
      if (!userStore.userBehavior && userStore.getUserInfo?.accountType !== 'ADMIN') {
        userStore.setuserBehavior(new behavior(() => {
          message.error('长时间未操作');
          userStore.logout(true)
        }, addSubjectForm.value) as any)
      }

      userStore.userBehavior?.onStopDeactivated();
      userStore.userBehavior?.onStartDeactivated();
    }

    // Whitelist can be directly entered
    if (whitePathList.includes(to.path as PageEnum)) {
      if (to.path === LOGIN_PATH && token) {
        const isSessionTimeout = userStore.getSessionTimeout
        try {
          await userStore.afterLoginAction()
          if (!isSessionTimeout) {
            next((to.query?.redirect as string) || '/')
            return
          }
        } catch { }
      }
      next()
      return
    }

    // token does not exist
    if (!token) {
      // You can access without permission. You need to set the routing meta.ignoreAuth to true
      if (to.meta.ignoreAuth) {
        next()
        return
      }

      // redirect login page
      const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
        path: LOGIN_PATH,
        replace: true,
      }
      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path,
        }
      }
      next(redirectData)
      return
    }

    // Jump to the 404 page after processing the login
    if (
      from.path === LOGIN_PATH &&
      to.name === PAGE_NOT_FOUND_ROUTE.name &&
      to.fullPath !== (userStore.getUserInfo.homePath || PageEnum.BASE_HOME)
    ) {
      next(userStore.getUserInfo.homePath || PageEnum.BASE_HOME)
      return
    }

    // get userinfo while last fetch time is empty
    if (userStore.getLastUpdateTime === 0) {
      try {
        await userStore.getUserInfoAction()
      } catch (err) {
        next()
        return
      }
    }

    if (permissionStore.getIsDynamicAddedRoute) {
      next()
      return
    }

    const routes = await permissionStore.buildRoutesAction()

    routes.forEach(route => {
      router.addRoute(route as unknown as RouteRecordRaw)
    })

    router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw)



    permissionStore.setDynamicAddedRoute(true)

    if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
      // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
      next({ path: to.fullPath, replace: true, query: to.query })
    } else {
      const redirectPath = (from.query.redirect || to.path) as string
      const redirect = decodeURIComponent(redirectPath)
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
      next(nextData)
    }
  })
}
